/**
 * @class CompanyManager.workspace
 * NEEDS DESCRIPTION
 * <br />
 * @constructor
 * @singleton
 **/
FieldServiceDatabase.workspace = function(){
    var viewport, testgridpanel, projectlist_panel, testingdetail_panel, query_window;
    
    
    return {
        init: function(){
            this.buildViewport();
            //projectlist click on form
            projectlist_panel.getSelectionModel().on('selectionchange', function(sm, node){
                if (node.isLeaf()) {
                    testgrid_panel.setTitle(String.format('{0}({1})', node.attributes.project_name, node.attributes.project_number))
                    var form_id = node.id.split('--')[2];
					
                    var params = {
                        'project_number': node.attributes.project_number,
                        'start': 0,
                        'limit': FieldServiceDatabase.PAGESIZE,
                        'sort': 'test_no',
                        'dir': 'ASC'
                    
                    }
					var store = testgrid_panel.getStore();
					store.setBaseParam('project_number', node.attributes.project_number)
					store.setBaseParam('client_name', '');
					store.setBaseParam('from_dt', '');
					store.setBaseParam('to_dt', '');
					store.setBaseParam('project_name', '');
					
					
                    testgrid_panel.getStore().load({
                        params: params
                    });
                }
                
                
            });
            //show details of a testing when clicked
            testgrid_panel.getSelectionModel().on('rowselect', function(sm, rowIdx, r){
            
                var html = '<table border="0.5" style="font-size: 10px">';
                for (var name in r.data) {
                    html = html + '<tr><td>' + name + '</td><td>' + r.data[name] + '</td></tr>'
                };
                html = html + '</table>';
                Ext.getCmp('testing-detail-panel').body.update(html);
            });
            //download the testgrid data as csv
            testgrid_panel.download_button.on('click', function(){
                if (testgrid_panel.getStore().getTotalCount() == 0) {
                    Ext.MessageBox.alert('Warning', 'No records available for download. Please select a form or create a new query.')
                    
                }
                else {
                    var options = testgrid_panel.getStore().lastOptions;
                    //location.href = '/download?format=csv&' + Ext.urlEncode(options.params)
                    window.open('/download?table_name=asphalt_test&' + Ext.urlEncode(options.params), 'Download')
                }
                
            });
            testgrid_panel.report_button.on('click', function(){
                if (testgrid_panel.getStore().getTotalCount() == 0) {
                    Ext.MessageBox.alert('Warning', 'No records available for download. Please select a form or create a new query.')
                    
                }
                else {
                    var options = testgrid_panel.getStore().lastOptions;
					var base_params = testgrid_panel.getStore().baseParams;
                    //location.href = '/download?format=csv&' + Ext.urlEncode(options.params)
                    window.open('/report?tableid=asphalt_test&' + Ext.urlEncode(options.params) + '&' + Ext.urlEncode(base_params.params), 'Report')
                }
                
            });
			//edit projects
			var edit_button = Ext.getCmp('button-edit');
			edit_button.on('click', function(){
				window.open('/projecteditor', 'Project Editor')
			})
            //show query window when button clicked
            var query_button = Ext.getCmp('button-new-invoice');
            query_button.on('click', function(){
                if (query_window) {
                    query_window.show()
                }
                else {
                    query_window = new FieldServiceDatabase.QueryWindow({
                        store: testgrid_panel.getStore()
                    });
                    query_window.show()
                }
            });
            //upload window
            var upload_window = null;
            //upload button
            var upload_button = Ext.getCmp('button-upload');
            upload_button.on('click', function(){
                if (upload_window) {
                    upload_window.show()
                }
                else {
                    upload_window = new FieldServiceDatabase.UploadWindow({
						 url: '/upload?action=update_asphalt_test'
					});
                    upload_window.show()
                }
            })
            
            
        },
        
        buildViewport: function(){
            var columns = [new Ext.grid.RowNumberer(), {
                id: 'id',
                header: "id",
                width: 60,
                sortable: true,
                dataIndex: 'id',
                hidden: true
            }, {
                header: "Client Name",
                width: 50,
                sortable: true,
                dataIndex: 'client_name',
                hidden: true
            
            }, {
                header: "By",
                width: 50,
                sortable: true,
                dataIndex: 'tested_by',
                hidden: true
            
            }, {
                header: "Project Name",
                width: 50,
                sortable: true,
                dataIndex: 'project_name_full',
                hidden: true
            
            }, {
                header: "Project Number",
                width: 50,
                sortable: true,
                dataIndex: 'project_number',
                hidden: true
            
            }, {
                header: "Test No",
                width: 35,
                sortable: true,
                dataIndex: 'test_no',
                hidden: false
            
            }, {
                header: "Report Test No",
                width: 35,
                sortable: true,
                dataIndex: 'report_test_no',
                hidden: false
            
            }, {
                header: "Date",
                width: 50,
                sortable: true,
                dataIndex: 'form_date',
                renderer: Ext.util.Format.dateRenderer('m/d/y'),
                hidden: false
            }, {
                header: "Location",
                width: 60,
                sortable: true,
                dataIndex: 'test_location',
                hidden: false
            }, {
                header: "Interval",
                width: 50,
                sortable: true,
                dataIndex: 'test_interval',
                hidden: false
            }, {
                header: "Wet Unit Weight",
                width: 35,
                sortable: true,
                dataIndex: 'wet_unit_weight',
                hidden: false
            }, {
                header: "Curve No.",
                width: 30,
                sortable: true,
                dataIndex: 'curve_no',
                hidden: false
            }, {
                header: "Max dry unit weight",
                width: 35,
                sortable: true,
                dataIndex: 'max_dry_unit_weight',
                hidden: false
            }, {
                header: "Specified(%)",
                width: 30,
                sortable: true,
                dataIndex: 'specified',
                hidden: false
            }, {
                header: "Obtained(%)",
                width: 35,
                sortable: true,
                dataIndex: 'obtained',
                hidden: false
            }, {
                header: "Remarks",
                width: 50,
                sortable: true,
                dataIndex: 'remarks',
                hidden: false
            }];
            
            testgrid_panel = new FieldServiceDatabase.TestGrid({
                store: new Ext.data.JsonStore({
                    proxy: new Ext.data.HttpProxy({
                        url: '/testings?tableid=asphalt_test'
                    }),
                    remoteSort: true
                
                }),
                columns: columns,
                plugins: new Ext.ux.grid.ColumnHeaderGroup({
                    rows: [[{
                        header: 'No',
                        colspan: 6,
                        align: 'center'
                    }, {
                        header: 'General',
                        colspan: 5,
                        align: 'center'
                    }, {
                        header: 'Field Test Data',
                        colspan: 1,
                        align: 'center'
                    }, {
                        header: 'Control Data',
                        colspan: 2,
                        align: 'center'
                    }, {
                        header: 'Compaction',
                        colspan: 2,
                        align: 'center'
                    }, {
                        header: 'Results',
                        colspan: 1,
                        align: 'center'
                    }]]
                })
            });
            projectlist_panel = new FieldServiceDatabase.ProjectList();
            testingdetail_panel = new Ext.Panel({
                region: 'center',
                id: 'testing-detail-panel',
                title: 'Testing Detail',
                autoScroll: true
            
            });
            
            viewport = new Ext.Viewport({
                layout: 'border',
                items: [new Ext.BoxComponent({ // raw element
                    region: 'north',
                    el: 'header',
                    height: 25
                    //			bodyStyle: 'padding:5px 5px 15px 5px'
                }), //west panel
                {
                    layout: 'border',
                    id: 'west-panel',
                    region: 'west',
                    border: true,
                    collapsible: true,
                    collapseMode: 'mini',
                    hideCollapseTool: true,
                    split: true,
                    margins: '2 0 5 5',
                    width: 275,
                    minSize: 100,
                    maxSize: 500,
                    items: [projectlist_panel, testingdetail_panel]
                }, //center
                {
                
                    region: 'center', // this is what makes this panel into a region within the containing layout
                    layout: 'border',
                    margins: '2 2 2 0',
                    split: true,
                    border: false,
                    items: [testgrid_panel]
                }, new Ext.BoxComponent({ // raw element
                    region: 'south',
                    el: 'footer',
                    height: 16
                })]
            });
        }
    }
}();


Ext.onReady(FieldServiceDatabase.workspace.init, FieldServiceDatabase.workspace);
